/**
 * Created by Administrator on 2015/5/5.
 */
var Schema = require('mongoose').Schema;
var model = require('../model/model').model;
var Promise = require('promise');
var utils = require('../utils');
var app = require('../config').globalApp;
var querystring = require('querystring');
var dao = require('../model/dao').PromiseDao;
module.exports = {
    register: function (req, res) {
        var params = req.body;
        var pwd = utils.MD5(params.password);

        if(params.verifyCode !== 'verify'){
            res.json({ret: -1}).end();
            return;
        }
        var User = new model.UserModel({
            username: params.username,
            password: pwd
        });
        dao.save(User).then(function () {
                res.json({ret: 1}).end();
            }, function () {
                res.json({ret: -1}).end();
            });

    },
    /**
     * 检查用户名是否存在
     * @param req
     * @param res
     * @param username
     * @return 1:存在 -1不存在
     */
    check: function (req, res, username) {
        if (!username) {
            res.status(400).end('请求参数有误');
        } else {
            dao.findOne(model.UserModel, {username: username}).then(function (doc) {
                var ret = -1;
                if (doc) {
                    ret = 1;
                }
                res.json({ret: ret}).end();
            }, function (err) {
                res.status(500).end(err);
            });
        }
    },
    /**
     * @param req
     * @param res
     * @return -1: 登录失败 1:成功
     */
    login: function (req, res) {
        var params = req.body;
        console.log(params);
        dao.findOne(model.UserModel, {username: params.username || ''}).then(function (doc) {
            var ret = -1;

            if (doc) {
                var password = utils.MD5(params.password || '');
                if(doc.password === password){
                    req.session.user = {username: doc.username, id: doc.id};
                    ret = 1;
                }
            }
            res.json({ret: ret}).end();
        }, function (err) {
            res.status(500).end(err);
        });
    },
    logout: function(req, res){
        req.session = null;
        res.redirect('/');
    }
};
